package com.shh.aiojbackendserver.rabbmitmq;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.shh.aiojbackendserver.judge.JudgeService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import static com.shh.aiojbackendserver.constant.RabbmitMqConstant.DLX_QUEUE_NAME;
import static com.shh.aiojbackendserver.constant.RabbmitMqConstant.QUEUE_NAME;
import com.shh.aiojbackendserver.model.entity.User;


/**
 * 确认消息已成功处理
 * 消息会被从队列中移除
 * channel.basicAck(deliveryTag, false);
 *
 *
 * 更强大的拒绝方法，可以批量拒绝消息
 * 提供了更多控制选项
 * channel.basicNack(deliveryTag, false, false);
 */
@Slf4j
@Component
public class MyMessageConsumer {
    @Resource
    private JudgeService judgeService;

    // 指定程序监听的消息队列queues = {"code_queue"}
    // 和确认机制
    @SneakyThrows
    @RabbitListener(queues = {QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
//        long questionSubmitId = Long.parseLong(message);
        JSONObject jsonObject = JSONUtil.parseObj(message);
        // 安全获取long值
        long questionSubmitId = jsonObject.getLong("questionSubmitId");
        long userId = jsonObject.getLong("userId");
        try {
            judgeService.doJudge(questionSubmitId,userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("处理消息失败，消息将进入死信队列", e);
            // 第三个参数为requeue，设为false表示不重新入队，而是进入死信队列
            channel.basicNack(deliveryTag, false, false);
        }
    }

    // 死信队列消费者（可选）
    @SneakyThrows
    @RabbitListener(queues = {DLX_QUEUE_NAME}, ackMode = "MANUAL")
    public void processFailedMessages(String message, Channel channel,
                                      @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.warn("收到死信消息: {}", message);
        // 这里可以添加处理死信消息的逻辑，比如记录日志、发送通知等
        try {
            // 处理死信消息...
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("处理死信消息失败", e);
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
